<script setup>
import portalUserService from '@/services/portal-user.service';
import { AxiosError } from 'axios';
import { ElLoading, ElMessage, ElMessageBox, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElButton, ElUpload } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Search, Refresh, Plus, Edit, Delete, View, Upload, Download, Share, Close } from "@element-plus/icons-vue";
import { Lock } from "@element-plus/icons-vue";

const createDefaultSearchEntity = () => {
    const e = {};
    return e;
}

const router = useRouter();
const route = useRoute();
const page = ref();
const selections = ref([]);
const searchEntity = ref(createDefaultSearchEntity());
const tableLoading = ref(false);

const load = async (no, size, searchObj) => {
    try {
        tableLoading.value = true;
        const res = await portalUserService.page(no, size, searchObj);
        page.value = res;
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {
        tableLoading.value = false;
    }
}

const search = () => {
    load(1, page.value.size, searchEntity.value);
};

const clearSearch = () => {
    searchEntity.value = createDefaultSearchEntity();
    load(1, page.value.size, searchEntity.value);
};

const create = () => {
    router.push({
        path: "/user-detail",
        query: {
            operation: 'CREATE'
        }
    });
};

const edit = () => {
    if (selections.value.length == 0 || selections.value.length > 1) {
        ElMessage({ message: "请选择一条数据", type: "error" });
        return;
    }

    const row = selections.value[0];
    editRow(row);
};

const remove = async (row) => {
    let ids = [];
    if (row != null) {
        ids = [row.id];
    } else {
        ids = selections.value.map(it => it.id);
    }
    if (ids.length == 0) {
        ElMessage({ message: "请选择要删除的数据", type: "error" });
        return;
    }
    try {
        const flag = await ElMessageBox.confirm('确定要删除选中的数据吗');
        if (flag) {
            await portalUserService.remove(ids);
            ElMessage({ message: "删除成功", type: "success" });
            load(undefined, page.value.size);
        }
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {

    }
};

const exportData = async () => {
    try {
        const flag = await ElMessageBox.confirm('确定要导出全部数据吗');
        if (flag) {
            await portalUserService.exportData();
            ElMessage({ message: "导出成功", type: "success" });
            load(undefined, page.value.size);
        }
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {

    }
}

const importData = async (options) => {
    try {
        const flag = await ElMessageBox.confirm('确定要导入数据吗');
        if (flag) {
            return portalUserService.importData(options.file);
        } else {
            return Promise.resolve(false);
        }
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {

    }
};

const onImportDataSuccess = async () => {
    ElMessage({ message: "导出成功", type: "success" });
    await load(undefined, page.value.size);
}

const editRow = (row) => {
    router.push({
        path: "/user-detail",
        query: {
            operation: 'EDIT',
            id: row.id,
        }
    });
};

const removeRow = (row) => {
    remove(row);
};

const resetPassword = async (row) => {
    const ids = selections.value.map(it => it.id);
    try {
        const flag = await ElMessageBox.confirm('确定要重置密码吗');
        if (flag) {
            await portalUserService.resetPassword(row.id);
            ElMessage({ message: "重置成功", type: "success" });
            load(undefined, page.value.size);
        }
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            ElMessage({ message: msg, type: "error" });
        }
        throw err;
    } finally {

    }
};

const selectionChanged = (val) => {
    selections.value = val;
}

const pageChanged = async (no) => {
    await load(no, page.value.size, searchEntity.value);
}

const pageSizeChanged = async (size) => {
    await load(1, size, searchEntity.value);
}

onMounted(async () => {
    await load();
});
</script>

<template>
    <ElForm size="small" inline>
        <ElFormItem label="用户名">
            <ElInput v-model="searchEntity.username"></ElInput>
        </ElFormItem>
        <ElFormItem label="昵称">
            <ElInput v-model="searchEntity.nickname"></ElInput>
        </ElFormItem>
        <ElFormItem label="邮箱">
            <ElInput v-model="searchEntity.email"></ElInput>
        </ElFormItem>
        <ElFormItem label="手机号">
            <ElInput v-model="searchEntity.phone"></ElInput>
        </ElFormItem>
        <ElFormItem label="启用状态">
            <ElRadioGroup v-model:model-value="searchEntity.status">
                <ElRadio :label="undefined">不限</ElRadio>
                <ElRadio :label="1">是</ElRadio>
                <ElRadio :label="0">否</ElRadio>
            </ElRadioGroup>
        </ElFormItem>
        <ElFormItem>
            <ElButton type="primary" :icon="Search" @click="search()">搜索</ElButton>
            <ElButton :icon="Refresh" @click="clearSearch()">清空</ElButton>
        </ElFormItem>
    </ElForm>
    <div class="flex">
    </div>
    <ElTable row-key="id" :data="page.content" @selection-change="selectionChanged($event)" v-loading="tableLoading">
        <ElTableColumn type="selection" width="55" />
        <ElTableColumn prop="username" label="用户名"></ElTableColumn>
        <ElTableColumn prop="nickname" label="昵称"></ElTableColumn>
        <ElTableColumn prop="email" label="邮箱"></ElTableColumn>
        <ElTableColumn prop="phone" label="手机号"></ElTableColumn>
        <ElTableColumn prop="createdTime" label="创建时间"></ElTableColumn>
        <ElTableColumn prop="operation" label="操作">
            <template #default="scope">
            </template>
        </ElTableColumn>
    </ElTable>
    <ElPagination layout="prev, pager, next, sizes, jumper, total" :total="Number(page.totalElements)"
        :current-page="page.number" :page-size="page.size" :page-sizes="[10, 30, 50, 100, 200]"
        @current-change="pageChanged($event)" @size-change="pageSizeChanged($event)" />
</template>

<style scoped lang="scss"></style>